<template>
  <div>
    <list-header title="选择品类">
      <el-radio-group
        v-model="selectWays.val"
        slot="right"
        size="mini"
        @change="handleChangeSelectWays"
      >
        <el-radio-button
          v-for="item in selectWays.options"
          :label="item.value"
          :key="item.value"
        >{{ item.label }}
        </el-radio-button>
      </el-radio-group>
    </list-header>
    <select-container-box>
      <template v-if="selectWays.val == selectWays.values.Search">
        <SelectSearch
          ref="cslRef"
          slot="box-search"
          showSearchCode
          :searchName.sync="searchData.categoryName"
          :searchCode.sync="searchData.categoryNo"
          @searchData="getCategoryListBySearch"
        />
        <select-show-list slot="box-list">
          <el-checkbox-group v-model="checkCodeList" v-loading="searchLoading" @change="handleSelectCategory">
            <div v-for="cateInfo in categoryList" :key="cateInfo.categoryNo">
              <el-checkbox :label="cateInfo.categoryNo">
                {{ cateInfo.categoryName }} &nbsp;&nbsp; {{ cateInfo.categoryNo }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </select-show-list>
      </template>
      <template v-if="selectWays.val == selectWays.values.Tree">
        <select-show-list slot="box-list">
          <SelectTree
            ref="tsRef"
            @checkTreeNodes="updateCheckNodes"
          />
        </select-show-list>
      </template>
    </select-container-box>
  </div>
</template>
<script>
import ListHeader from './ListHeader';
import SelectSearch from './SelectSearch';
import SelectContainerBox from './SelectContainerBox';
import SelectShowList from './SelectShowList';
import SelectTree from './SelectTree';
import { getCategoryListByKeyService } from '@/api/public';
import { eventBus } from '../eventBus';
import { SELECT_WAYS_OPTIONS, SELECT_WAYS_VALUES } from '../constant';
import { getArraysByMaps } from '@/utils/getUtils';
export default {
  components: {
    ListHeader,
    SelectContainerBox,
    SelectSearch,
    SelectShowList,
    SelectTree
  },
  data () {
    return {
      checkCodeList: [],
      categoryList: [],
      checkCateMaps: new Map(),
      searchData: { categoryName: '', categoryNo: '' },
      selectWays: {
        options: SELECT_WAYS_OPTIONS,
        values: SELECT_WAYS_VALUES,
        val: SELECT_WAYS_VALUES.Search
      },
      searchLoading: false
    }
  },
  created () {
    // 更新已勾选品类数据
    eventBus.$on('updateSelectCategiries', codes => {
      this.checkCodeList = codes
      this.checkCateMaps = this.checkCodeList.reduce((newMap, code) => {
        if (this.checkCateMaps.has(code)) {
          newMap.set(code, this.checkCateMaps.get(code))
        }
        return newMap
      }, new Map())
      // 设置回显勾选节点
      eventBus.$emit('setCheckedNodes', this.checkCodeList)
    })
  },
  methods: {
    // 获取查询获取品类查询集合
    getCategoryListBySearch () {
      this.handleSearchCategoryList()
    },
    // 查询品类集合
    async handleSearchCategoryList () {
      const data = {
        key: this.searchData.categoryName,
        categoryNo: this.searchData.categoryNo
      }
      const loadingFn = state => { this.searchLoading = state }
      const res = await getCategoryListByKeyService(data, loadingFn)
      if (!res) return
      if (res.retData && res.retData.length == 0) {
        this.categoryList = []
        return this.$message.warning('未查询到品类信息')
      }
      this.categoryList = res.retData
      this.handleSelectCategory(this.checkCodeList)
    },
    // 选择品类
    handleSelectCategory (codeList) {
      const categoryMaps = new Map(this.categoryList.map(item => [item.categoryNo, item])) // 当前搜索结果的集合Map
      codeList.forEach(code => {
        if (categoryMaps.has(code)) { // 当前勾选编码结果存在于搜索结果集中，便将该项添加至勾选Map结果集中
          this.checkCateMaps.set(code, categoryMaps.get(code))
        }
      })
      this.checkCateMaps.forEach((value, key) => {
        if (!codeList.includes(key)) { // 当前勾选编码结果不包含勾选Map的code时，便从勾选Map移除该项
          this.checkCateMaps.delete(key)
        }
      })
      eventBus.$emit('selectCategory', this.checkCateMaps)
    },
    // 清空品类搜索结果
    clearResults () {
      this.$refs?.cslRef?.clearSearchState && this.$refs.cslRef.clearSearchState()
      this.checkCodeList = []
      this.categoryList = []
      this.checkCateMaps = new Map()
      eventBus.$emit('selectCategory', this.checkCateMaps)
    },
    // 切换选择品类方式
    handleChangeSelectWays (val) {
      if (val === SELECT_WAYS_VALUES.Tree) {
        const checkedKeys = getArraysByMaps(this.checkCateMaps).map(item => item.categoryNo).filter(item => item)
        eventBus.$emit('setCheckedNodes', checkedKeys)
        eventBus.$emit('loadRootTreeData')
      }
    },
    // 更新已勾选品类节点集合
    updateCheckNodes (nodeMaps) {
      this.checkCateMaps = new Map([...this.checkCateMaps, ...nodeMaps])
      this.checkCodeList = getArraysByMaps(this.checkCateMaps).map(item => item.categoryNo)
      eventBus.$emit('selectCategory', this.checkCateMaps)
    }
  }
}
</script>
